package com.easepal7506a.project.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.easepal7506a.project.Constant.CommmandNum;
import com.easepal7506a.project.R;
import com.easepal7506a.project.manager.DataManager;
import com.easepal7506a.project.observer.CloseAdvance;
import com.easepal7506a.project.ui.iview.IFraMassageView7506;
import com.easepal7506a.project.ui.presenter.FraMassagePresenter7506;
import com.easepal7506a.project.view.LongClickImageView2;
import com.easepal7506a.project.view.MoveLayout;
import com.easepal7506a.project.widget.LayoutGears5_7506;
import com.easepal7506a.project.widget.LayoutGears6_7506;
import com.example.reslib.utils.ToastUtils;
import com.ogawa.base.utils.CommonUtil;
import com.ogawa.base.utils.DownTimer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**按摩手法
 * Created by LCH on 2018/1/29.
 */
public class MassageTechniqueFragment extends BaseTimeTaskFragment implements LongClickImageView2.onDownAction
        ,View.OnClickListener,MoveLayout.OnChooseAction,IFraMassageView7506 {


    private View inflate;

    private RelativeLayout mLl3D;
    private RelativeLayout mLlDynamics;//力度
    private RelativeLayout mLlSpeed;
    private LinearLayout mLlSelectSkill;//选择手法
    private TextView tvTime;
    private FraMassagePresenter7506 mPresenter;

    private TextView mTvFix;//定点，区间 全身
    private int flag_area = 0;//0 mTvFix 关闭（默认定点），1 定点开 2 区间 3 全身
    private int[] mRnImage = {R.drawable.hand_knead_normal_selector, R.drawable.hand_knead1_selector,R.drawable.hand_knead2_selector};//揉捏
    private int[] mQJImage = {R.drawable.hand_tap0_selector,R.drawable.hand_tap1_selector,R.drawable.hand_tap2_selector};//敲击
    private int[] mTNImage = {R.drawable.hand_roll_normal_selector,R.drawable.hand_roll_selected_selector};//推拿

    private int[] mPDImage = {R.drawable.hand_paida0_selector,R.drawable.hand_paida1_selector,R.drawable.hand_paida2_selector};//拍打
    private int[] mZYImage = {R.drawable.hand_zhiya0_selector,R.drawable.hand_zhiya1_selector,R.drawable.hand_zhiya2_selector};//指压
    private int[] mRDSImage = {R.drawable.hand_rds0_selector,R.drawable.hand_rds1_selector,R.drawable.hand_rds2_selector};//瑞典式

    private List<int[]> mImages = new ArrayList<>();


    private ImageView mHeadup;//up
    private  ImageView  mHeadDown;//DOWN
    private ImageView mIvWidthNoClick;//

    private  FrameLayout mFlwidth;//宽度背景
    private ImageView mIvLeft,mIvRight;//宽度加减
    private ImageView mIvRN;//揉捏
    private ImageView mIvQJ;//敲击
    private ImageView mIvPD;//拍打
    private ImageView mIvRDS;//瑞典式
    private ImageView mIvZY;//指压
    private ImageView mIvTN;//推拿
    private List<ImageView> mIvSkills = new ArrayList<>();
    private String[] name = {"手法","3D","力度","速度"};


    private LayoutGears6_7506 mLayout3D;
    private LayoutGears5_7506 mLayoutPower;
    private LayoutGears5_7506 mLayoutSpeed;
    private MoveLayout mLayout;
    private ScrollView mScroll;
    //机芯调节
    private boolean isClickUpOrDown =false;
    private long mClickUpDownTime =0;
    private String mActionUpDown ="";//按上up   按下dowm
    private Disposable mDisposable;
    private int mPoint;//机芯位置
    //宽度调节
    private boolean isClickWidth =false;
    private long mClickWidthTime  =0;
    private String mActionWidth ="";//按左left   按右right
    private Disposable mDisposableWidth;
    private int mWidth;//
    private long mTime;
    private DownTimer mTimer;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        inflate = inflater.inflate(R.layout.fragment_massage_technique_7506, container, false);
        initView();

        return inflate;
    }



    private void initView() {
        if(!TextUtils.isEmpty(DataManager.getInst().getValue(CommmandNum.mStatusWidth))){
            mWidth=Integer.valueOf(DataManager.getInst().getValue(CommmandNum.mStatusWidth)) ;
        }
        if(!TextUtils.isEmpty(DataManager.getInst().getValue(CommmandNum.mStatusPointPosition))){
            mPoint=Integer.valueOf(DataManager.getInst().getValue(CommmandNum.mStatusPointPosition)) ;
        }

        mHeadup  = inflate.findViewById(R.id.headup);
        mHeadDown= inflate.findViewById(R.id.headdown);
        mScroll =  inflate.findViewById(R.id.massage_fragment_scroll);
        mLayout=  inflate.findViewById(R.id.massege_fragment_move_layout);
        mIvWidthNoClick=  inflate.findViewById(R.id.iv_width_noclick);
        mLayout.setData(name);
        mLayout.setScollView(mScroll);
        mLayout.setAction(this);

        mHeadup.setOnClickListener(this);

        mHeadDown.setOnClickListener(this);

        mIvLeft  =  inflate.findViewById(R.id.iv_width_left);


        mIvRight =  inflate.findViewById(R.id.iv_width_right);
        mIvLeft.setOnClickListener(this);
        mIvRight.setOnClickListener(this);
        mFlwidth = inflate.findViewById(R.id.fragment_mt_fl_width);
        tvTime   = inflate.findViewById(R.id.tvTime);


        mIvRN = inflate.findViewById(R.id.fragment_mt_tv_knead);
        mIvQJ = inflate.findViewById(R.id.fragment_mt_tv_tap);
        mIvPD = inflate.findViewById(R.id.fragment_mt_tv_paida);
        mIvRDS = inflate.findViewById(R.id.fragment_mt_tv_swedish);
        mIvZY = inflate.findViewById(R.id.fragment_mt_tv_shiatsu);
        mIvTN = inflate.findViewById(R.id.fragment_mt_tv_roll);
        mImages.clear();
        mIvSkills.clear();
        mImages.add(mRnImage);
        mImages.add(mQJImage);

        mImages.add(mTNImage);
        mImages.add(mZYImage);
        mImages.add(mPDImage);
        mImages.add(mRDSImage);

        mIvSkills.add(mIvRN);
        mIvSkills.add(mIvQJ);
        mIvSkills.add(mIvTN);
        mIvSkills.add(mIvZY);
        mIvSkills.add(mIvPD);
        mIvSkills.add(mIvRDS);


        mLayout3D    = inflate.findViewById(R.id.layout_3d);
        mLayoutPower = inflate.findViewById(R.id.linear_air_massage_strong);
        mLayoutSpeed = inflate.findViewById(R.id.linear_air_massage_speed);
        mLayout3D.setType(1);
        mLayoutPower.setType(1);
        mLayoutSpeed.setType(2);

        mTvFix= inflate.findViewById(R.id.fragmentFixpoint);
        mTvFix.setOnClickListener(this);
        mLl3D = inflate.findViewById(R.id.layout_3d);
        mLlDynamics = inflate.findViewById(R.id.linear_air_massage_strong);
        mLlSpeed = inflate.findViewById(R.id.linear_air_massage_speed);
        mLlSelectSkill= inflate.findViewById(R.id.linear_methods_to_select);

        mIvLeft.setOnClickListener(this);
        mIvRight.setOnClickListener(this);

        mIvRN.setOnClickListener(this);
        mIvQJ.setOnClickListener(this);
        mIvPD .setOnClickListener(this);
        mIvRDS.setOnClickListener(this);
        mIvZY.setOnClickListener(this);
        mIvTN.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        mPresenter = new FraMassagePresenter7506(this);
        initData();
    }
    private void initData(){
        mPresenter.set3D(DataManager.getInst().getValue(CommmandNum.mStatus3D));
        mPresenter.setPower(DataManager.getInst().getValue(CommmandNum.mStatusStrength));
        mPresenter.setSpeed(DataManager.getInst().getValue(CommmandNum.mStatusSpeed));
        mPresenter.setknead(DataManager.getInst().getValue(CommmandNum.mStatusKnead));
        mPresenter.setHand(DataManager.getInst().getValue(CommmandNum.mStatusHand));
        mPresenter.setWidth(DataManager.getInst().getValue(CommmandNum.mStatusWidth));
        mPresenter.setDinddian();

    }

    public void initTime(String min,String sec){
        Log.e("Timetimetiem111",min+"==="+sec);
        setTime(Integer.valueOf(min),Integer.valueOf(sec));
    }
    public void upDataTime(String min,String sec){
        if(DataManager.getInst().isAdvanceRunning()||DataManager.getInst().isAutoRunning()) {
            if(!(min.equals("0")&&sec.equals("0"))){
                long time = (Integer.valueOf(min)*60+Integer.valueOf(sec));
                Log.e("Timetimetiem11122",mTime+"==="+time);
                if(Math.abs(time-mTime)>30){
                    Log.e("Timetimetiem11122",mTime+"==="+time);
                    setTime(Integer.valueOf(min),Integer.valueOf(sec));
                }
            }else {
                setTextView(tvTime,"00 : 00");
                mTime=0;
            }

        }else {
            cancelTime();
            setTextView(tvTime,"00 : 00");
            mTime=0;
        }



    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tvTime) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                showDialog();

            }


        }
        else if (i == R.id.headup) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if(mPoint<10){
                    mActionUpDown ="up";
                    setUpOrDown();
                    mPoint =Integer.valueOf(DataManager.getInst().getValue(CommmandNum.mStatusPointPosition)) ;
                    sendCommond(CommmandNum.JIXINUP);
                }else {
                    ToastUtils.showShortToast(getContext(),"机芯已在最高处");
                }

            }

        }
        else if (i == R.id.headdown) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if(mPoint>0){
                    mActionUpDown ="down";
                    setUpOrDown();
                    mPoint =Integer.valueOf(DataManager.getInst().getValue(CommmandNum.mStatusPointPosition)) ;
                    sendCommond(CommmandNum.JIXINDOWM);
                }else {
                    ToastUtils.showShortToast(getContext(),"机芯已在最低处");
                }

            }


        }



        else if (i == R.id.fragmentFixpoint) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.DINGDQUJ);

            }



        } else if (i == R.id.iv_width_left) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if(mWidth>0){
                    mActionWidth ="left";
                    setWidthClick();
                    sendCommond(CommmandNum.KUANDUSUB);
                }else {
                    ToastUtils.showShortToast(getContext(),"宽度已最小");
                }


            }

        } else if (i == R.id.iv_width_right) {
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                if(mWidth<3){
                    mActionWidth ="right";
                    setWidthClick();
                    sendCommond(CommmandNum.KUANDUADD);
                }else {
                    ToastUtils.showShortToast(getContext(),"宽度已最大");
                }
            }

        }  else if (i == R.id.fragment_mt_tv_knead) {//揉捏
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.ROUN);
            }

        } else if (i == R.id.fragment_mt_tv_tap) {//敲击
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.QIAOJ);
            }

        }
        else if (i == R.id.fragment_mt_tv_roll) {//推拿
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.TUINA);
            }


        }
        else if (i == R.id.fragment_mt_tv_paida) {//拍打
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.PAIDA);
            }

        }  else if (i == R.id.fragment_mt_tv_shiatsu) {//指压
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.ZHIYA);
            }

        }
        else if (i == R.id.fragment_mt_tv_swedish) {//瑞典
            if (CommonUtil.isFastClick()) {
                return;
            } else {
                sendCommond(CommmandNum.RUID);
            }

        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelTime();
        mPresenter.onDestory();
    }

    private void setWidth(int position){
        if(position==0){
            mFlwidth.setBackgroundResource(R.mipmap.width0);
        }
        else if(position ==1){
            mFlwidth.setBackgroundResource(R.mipmap.width1);
        }
        else if(position ==2){
            mFlwidth.setBackgroundResource(R.mipmap.width2);
        }
        else if(position ==3){
            mFlwidth.setBackgroundResource(R.mipmap.width3);
        }
        else {
            mFlwidth.setBackgroundResource(R.mipmap.width0);
        }

    }


    private void setArea(int position){
        if(position ==0){
            mTvFix.setSelected(false);
            mTvFix.setText("定点");
        }
        else   if(position ==1 ){
            mTvFix.setSelected(true);
            mTvFix.setText("定点");
        }
        else if(position ==2){
            mTvFix.setSelected(true);
            mTvFix.setText("区间");
        }

    }



    /**
     *
     * @param position 0揉捏，1敲击，2推拿，3敲揉，4指压，5瑞典；
     * @param stronger 强度
     */
    private synchronized void setSkill(int position, int stronger){
        mIvSkills.get(position).setImageResource(mImages.get(position)[stronger]);
    }

    @Override
    public void onChoose(int position) {
        mLayout.setTectColor(position);
        switch (position){
            case 0:
                mLlSelectSkill.setVisibility(View.VISIBLE);
                mLl3D.setVisibility(View.GONE);
                mLlSpeed.setVisibility(View.GONE);
                mLlDynamics.setVisibility(View.GONE);
                break;
            case 1:
                mLlSelectSkill.setVisibility(View.GONE);
                mLl3D.setVisibility(View.VISIBLE);
                mLlDynamics.setVisibility(View.GONE);

                mLlSpeed.setVisibility(View.GONE);
                break;
            case 2:
                mLlSelectSkill.setVisibility(View.GONE);
                mLl3D.setVisibility(View.GONE);
                mLlDynamics.setVisibility(View.VISIBLE);
                mLlSpeed.setVisibility(View.GONE);

                break;
            case 3:
                mLlSelectSkill.setVisibility(View.GONE);
                mLl3D.setVisibility(View.GONE);
                mLlDynamics.setVisibility(View.GONE);
                mLlSpeed.setVisibility(View.VISIBLE);

                break;
        }

    }

    @Override
    public void onDownClick(String what) {
        Log.e("LongNext","onDownClick");
        if (CommonUtil.isFastClick()) {
            return;
        } else {
//            BleController.getInst().sendLongclickSingleData(what,true);
        }
    }

    @Override
    public void getTime(String time) {
        sendTime(time);
    }

    @Override
    public void getWidth(int position) {
        mWidth =position;
        setWidth(position);
        if(isClickWidth){
            showwidth();
        }

    }

    @Override
    public void getArea(int position) {
        Log.e("getArea",position+"");
        setArea(position);
    }



    @Override
    public void get3D(int position) {
        mLayout3D.setShow(position);
        Log.e("getASSSSS+3d",position+"");
    }

    @Override
    public void getPower(int position) {
        mLayoutPower.setShow(position);
        Log.e("getASSSSS+Power",position+"");
    }

    @Override
    public void getSpeed(int position) {
        Log.e("getASSSSS+speed",position+"");
        mLayoutSpeed.setShow(position);
    }

    @Override
    public void getSkill(int position, int stronger) {
        setSkill(position,stronger);
    }

    @Override
    public void getPoint(int point) {
        //如果是点击了上
        if(!TextUtils.isEmpty(mActionUpDown)&& mActionUpDown.equals("up")){
            if(point>mPoint){
                showUpDown();
                mActionUpDown ="";
            }
        }
        else if(!TextUtils.isEmpty(mActionUpDown)&& mActionUpDown.equals("down")){
            if(point<mPoint){
                showUpDown();
                mActionUpDown ="";
            }
        }
        mPoint = point;
    }
    private void setUpOrDown(){
        isClickUpOrDown =true;
        mClickUpDownTime = System.currentTimeMillis();
        mHeadup.setEnabled(false);
        mHeadDown.setEnabled(false);
        intervalUpOrDown();
    }
    private void setWidthClick(){
        isClickWidth =true;
        mIvWidthNoClick.setVisibility(View.VISIBLE);
        mClickWidthTime = System.currentTimeMillis();
        mIvLeft.setEnabled(false);
        mIvRight.setEnabled(false);
        intervalWidth();
    }
    public void showUpDown(){
        isClickUpOrDown = false;
        mHeadup.setEnabled(true);
        mHeadDown.setEnabled(true);
        if(mDisposable!=null){
            mDisposable.dispose();
        }
    }
    public void showwidth(){
        isClickWidth = false;
        mIvWidthNoClick.setVisibility(View.GONE);
        mIvLeft.setEnabled(true);
        mIvRight.setEnabled(true);
        if(mDisposableWidth!=null){
            mDisposableWidth.dispose();
        }
    }



    /**
     * 单击上下调节3秒还没回复自动变为可点击
     */
    public void intervalUpOrDown(){
        Observable.interval(300,300, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                        mDisposable =d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        if(isClickUpOrDown &&System.currentTimeMillis()- mClickUpDownTime >3000){
                            showUpDown();

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showUpDown();

                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }
    /**
     * 单击宽度调节3秒还没回复自动变为可点击
     */
    public void intervalWidth(){
        Observable.interval(300,300, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.d("mmmTAG11111","当前线程：subscribe------"+Thread.currentThread().getName());
                        mDisposableWidth =d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        Log.d("mmmTAG2222","当前线程：subscribe------"+Thread.currentThread().getName());
                        if(isClickWidth &&System.currentTimeMillis()- mClickWidthTime >3000){

                            showwidth();

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showwidth();
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }
    public void pauseTime(){
        if(mTimer!=null){
            mTimer.pause();
        }

    }
    public void reStarTime(){
        if(mTimer!=null){
            mTimer.resume();
        }
    }
    public void cancelTime(){
        if(mTimer!=null){
            mTimer.cancel();
        }
    }

    public void setTime(int min,int sec){
        cancelTime();
        if(DataManager.getInst().isAdvanceRunning()||DataManager.getInst().isAutoRunning()){
            mTimer = new DownTimer();//实例化
            mTimer.setTotalTime(min*60*1000+sec*1000);//设置毫秒数
            mTimer.setIntervalTime(1000);//设置间隔数
            mTimer.setTimerLiener(new DownTimer.TimeListener() {
                @Override
                public void onFinish() {
                    setTextView(tvTime,"00 : 00");
                    mTime=0;
                    CloseAdvance.getInst().noticeonClose();
                }
                @Override
                public void onInterval(long time) {
                    long showTime =time/1000;
                    mTime = showTime;
                    if (showTime <= 59) {
                        setTextView(tvTime,String.format("00:%02d", showTime));
                    } else {
                        setTextView(tvTime,String.format("%02d:%02d", showTime / 60, showTime % 60));
                    }
                    if(!DataManager.getInst().isRunning()){
                        mTimer.cancel();
                        setTextView(tvTime,"00 : 00");
                    }
                }
            });
            mTimer.start();
        }else {
            mTimer.cancel();
            mTime=0;
            setTextView(tvTime,"00 : 00");


        }

    }

    private void  setTextView(TextView tv,String msg){
        if(tv!=null&&msg!=null){
            tv.setText(msg);
        }
    }




}
